<template>
  <div>
    <van-search
      v-model="params.name"
      placeholder="请输入主体名称"
      show-action
      @search="onSearch"
    >
      <img
        slot="action"
        class="filter"
        src="@/assets/img/icon/icon_filter.png"
        alt=""
        @click="onFilter"
      />
    </van-search>

    <div class="page_space">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <base-card
          v-for="(item, index) in list"
          :key="index"
          :data="item.data"
          :title="item.name"
          class="mt-15"
          @into="goto('/sampling-details')"
          @click="hitThis(item)"
        />
      </van-list>
    </div>

    <div v-if="list.length === 0" class="empty_tip">
      <img src="@/assets/img/empty.png" alt="" />
      <p>无数据</p>
    </div>

    <!-- <div class="btn_wrap">
      <button class="btn" @click="goto('/new-subject')">新增快检主体</button>
    </div> -->

    <van-popup v-model="showFilter" position="bottom">
      <!-- 选择产地-->
      <template v-if="showAddress">
        <van-cascader
          v-model="cascaderValue"
          title=""
          :options="places"
          @close="show = false"
          @change="onChange"
          @finish="onFinish"
        />
      </template>
      <template v-else>
        <div class="popup_input">
          <div class="popup_input_top">
            <span class="cancel">取消</span>
            <span class="title">筛选</span>
            <span class="confirm" @click="getSubjectName">确定</span>
          </div>
          <input-card>
            <inputItem
              v-model="params.areaCodeName"
              :content="params.areaCodeName"
              title="所属区划"
              tip="请选择所属区划"
              type="select"
              @select="selectAddress"
            />
            <inputItem
              v-model="params.managementEntName"
              title="所属市场"
              tip="请输入所属市场"
              type="input"
            />
            <inputItem
              v-model="params.uscId"
              title="统一社会信用代码/身份证号"
              tip="请输入统一社会信用代码/身份证号"
              type="input"
            />
          </input-card>
        </div>
      </template>
    </van-popup>
  </div>
</template>

<script>
import inputCard from '@/components/input-card/card'
import inputItem from '@/components/input-card/item'
import baseCard from '@/components/base-card'
import { getSubjectList } from '@/api/subject'
import { getAreaList } from '@/api/base'
import { store, mutations } from '@/observable'

export default {
  name: 'subjectList',
  components: { baseCard, inputCard, inputItem },
  data() {
    return {
      showFilter: false,
      loading: false,
      finished: false, // 触底加载结束
      params: {
        limit: 10,
        page: 1,
        subjectTypeNotIn: '',
        subjectType: '',
        auditStatus: 'auditSuccess',
        notFastCheckEnt: true,
        type: 'Merchant',
        enabled: true,
        managementEntName: '', // 所属市场
        name: '', // 主体名称
        uscId: '', // 营业执照/统一社会信用代码/身份证号
        areaCode: '', // 地区
        areaCodeName: ''
      },
      list: [],

      lastPage: '',
      showAddress: false, // 选择区划
      // 区划 区码
      cascaderValue: '',
      // 产地选项
      places: [],
      isFilter: false
    }
  },
  created() {
    this.lastPage = this.$route.query.lastPage || ''
    let subjectType = this.$route.query.subjectType || ''
    if (subjectType === 'TemporaryOperatingArea') {
      this.params.subjectType = 'TemporaryOperatingArea'
      this.params.subjectTypeNotIn = ''
    } else if (subjectType === 'FixedPlace') {
      this.params.subjectType = ''
      this.params.subjectTypeNotIn =
        'TemporarySurroundingArea,TemporaryOperatingArea'
    }
  },
  methods: {
    // 选中
    hitThis(e) {
      if (this.lastPage === 'new-inspectSubject') {
        let subject = e.origin
        let varietyTypeIds = []
        let varietyTypeIdsText = []
        subject.varietyTypeList.forEach((item) => {
          varietyTypeIds.push(item.varietyTypeId)
          varietyTypeIdsText.push(item.name)
        })
        let relationPlace = []
        subject.relationPlaceInfoList.forEach((item) => {
          relationPlace.push({
            enterpriseId: item.enterpriseId,
            placeId: item.placeId,
            contractNumber: item.contractNumber,
            foodSecurityPictureName: item.foodSecurityPictureName,
            foodSecurityPictureId: item.foodSecurityPictureId,
            securityProtocolPictureName: item.securityProtocolPictureName,
            securityProtocolPictureId: item.securityProtocolPictureId,
            placePictureId: item.placePictureId,
            placePictureName: item.placePictureName
          })
        })
        let info = {
          objectId: subject.id,
          name: subject.name,
          uscId: subject.uscId,
          areaName: subject.areaName,
          manageState: subject.manageState,
          manageStateText: subject.manageStateText,
          subjectNature: subject.subjectNature,
          subjectNatureText: subject.subjectNatureText,
          managementEntName: subject.belongEntName, // 所属市场
          managementEntId: subject.belongEntId,
          legalPerson: subject.legalPerson,
          contacts: subject.contacts,
          contactsTel: subject.contactsTel,
          home: subject.home,
          // varietyTypeList: subject.varietyTypeList,
          varietyTypeIds: varietyTypeIds.toString(),
          varietyTypeIdsText: varietyTypeIdsText.toString(),
          relationPlace: subject.relationPlace,
          auditStatus: subject.auditStatus,
          // 临时市场
          foundationDate: subject.foundationDate || '',
          hasEntryRecord: subject.hasEntryRecord || '',
          hasEntryRecordText: subject.hasEntryRecord === true ? '是' : '否',
          licenseNumber: subject.licenseNumber || ''
        }
        mutations.setSubjectInfo(info)
        console.log(info)
      }
      this.$router.go(-1)
    },
    // 触底加载
    onLoad() {
      this.getList(this.params)
    },
    async getList(params) {
      const res = await getSubjectList(params)
      if (res.code === '0') {
        res.data.content.forEach((item) => {
          this.list.push({
            name: item.name,
            id: item.id,
            data: [
              {
                key: '所属区划',
                value: item.areaName
              },
              {
                key: '营业执照/统一社会信用代码/身份证号',
                value: item.uscId
              }
            ],
            origin: item
          })
        })
        console.log(this.list)
        // 加载状态结束
        this.loading = false
        this.params.page++
        // 数据全部加载完成
        if (res.data.last) {
          this.finished = true
        }
      }
    },
    onSearch() {
      this.params.page = 1
      this.list = []
      this.getList(this.params)
    },
    // 过滤
    onFilter() {
      this.params.areaCodeName = ''
      this.params.areaCode = ''
      this.params.managementEntName = ''
      this.params.uscId = ''
      // 判断是否在过滤 非则清除过滤
      // if (this.isFilter) {
      //   this.params.page = 1
      //   this.list = []
      //   this.getList(this.params)
      //   this.isFilter = false
      // } else {
      //   this.showFilter = true
      // }

      // 最新
      this.showFilter = true
    },
    async selectAddress() {
      this.showAddress = true
      const { code, data } = await getAreaList({ parentAreaCode: 'CHN' })
      if (code === '0') {
        this.places = []
        data.forEach((item) => {
          this.places.push({
            text: item.areaName,
            value: item.areaCode,
            children: []
          })
        })
      }
    },
    // 选择-主体名称
    getSubjectName() {
      this.params.page = 1
      this.list = []
      this.getList(this.params)
      this.showFilter = false
      this.isFilter = true
      //
    },
    // 检测区划改变
    async onChange({ value, selectedOptions, tabIndex }) {
      const { code, data } = await getAreaList({
        parentAreaCode: value
      })
      let placeIndex = ''
      let target = {}

      if (tabIndex > 0) {
        for (let i = 0; i <= tabIndex; i++) {
          if (selectedOptions[i].parentIndex !== undefined) {
            let parentIndex = selectedOptions[i].parentIndex
            console.log('parentIndex:', parentIndex)
            target = this.places[parentIndex].children
          }
        }
        placeIndex = target.findIndex((item) => item.value === value)
        target = target[placeIndex]
      } else {
        placeIndex = this.places.findIndex((item) => item.value === value)
        target = this.places[placeIndex]
      }

      if (code === '0') {
        data.forEach((item) => {
          if (tabIndex < 1) {
            target.children.push({
              text: item.areaName,
              value: item.areaCode,
              children: [],
              parentIndex: placeIndex
            })
          } else {
            target.children.push({
              text: item.areaName,
              value: item.areaCode,
              parentIndex: placeIndex
            })
          }
        })
      }
    },
    // 区划完成
    onFinish({ selectedOptions }) {
      this.params.areaCodeName =
        selectedOptions.map((option) => option.text).join('') || ''
      // 获取区划码
      this.params.areaCode = selectedOptions[selectedOptions.length - 1].value
      console.log('finish')
      console.log(selectedOptions.map((option) => option.text).join('') || '')
      console.log(this.params.areaCodeName)
      this.showAddress = false
    }
  }
}
</script>

<style scoped lang="scss">
.filter {
  width: 20px;
  height: 20px;
}
.popup_input {
  &_top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px;
    .cancel {
      font-size: 14px;
      color: #b2b8bd;
    }
    .title {
      font-size: 16px;
      /* 文字/常规黑(描述类文字) */
      color: #171819;
    }
    .confirm {
      font-size: 14px;
      color: #2163e0;
    }
  }
}
.empty_tip {
  text-align: center;
  margin-top: 50px;

  font-family: PingFang SC Medium;
  font-size: 14px;
  font-weight: normal;
  line-height: 19px;
  letter-spacing: 0px;
  color: #b2b8bd;
}
</style>
